package com.ithema.reggie.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import com.ithema.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;

@RestController
@RequestMapping("common")
public class CommonController {

    @Value("${reggie.path}")
    String dirpath;

    @PostMapping("upload")
    public R upload(MultipartFile file) throws IOException {
        //1.指定存放文件的目录(若不存在则创建)
        File dirPath = new File(dirpath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }

        //2.获取文件的名字
        String filename = file.getOriginalFilename();

        //2.1 为了避免同名文件被覆盖,需要给文件起个唯一名称(建议使用uuid),但是我们还需要获取后缀名
        String extName = FileUtil.extName(filename);// jpg
        filename = IdUtil.fastUUID() + "." + extName;//使用hutool获取唯一uuid和后缀名

        //3.文件拷贝
        file.transferTo(new File(dirPath,filename));

        //4.返回文件名
        return R.success(filename);
    }

    @GetMapping("download")
    public void download(String name, HttpServletResponse response) throws IOException {

        //1.获取输入流
        FileInputStream is = new FileInputStream(dirpath + name);

        //2.获取输出流，对拷
        ServletOutputStream os = response.getOutputStream();
        IoUtil.copy(is,os);

        //3.释放资源
        is.close();
        os.close();
    }
}
